import { add } from "../../api/index.js";
var app = getApp();
Page({
  data: {
    choose: false,
    imgPath: "../../img/pic.png",
    imgPath2: "",
    imgPath3: "",
    imgLen: 0,
    temp: [],
  },
  choose: function () {
    this.setData({
      choose: !this.data.choose,
    });
  },
  choosePic: function () {
    console.log(this.data.temp);
    var that = this;
    if (this.data.imgPath == "../../img/pic.png") {
      wx.chooseImage({
        count: 3,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success: function (res) {
          var len = res.tempFilePaths.length;
          var temp = [
            that.data.imgPath2,
            that.data.imgPath3,
            that.data.imgPath,
          ];
          if (that.data.imgLen == 0) {
            for (var i = 0; i < len; i++) {
              temp[i] = res.tempFilePaths[i];
            }
          } else {
            for (var i = that.data.imgLen, j = 0; j < len && i < 3; i++, j++) {
              temp[i] = res.tempFilePaths[j];
              console.log(temp);
            }
          }
          var len2 = len + that.data.imgLen;
          if (len2 > 3) {
            len2 = 3;
          }
          that.setData({
            imgLen: len2,
            temp: temp,
            imgPath2: temp[0],
            imgPath3: temp[1],
            imgPath: temp[2],
          });
        },
      });
    }
  },
  bindTextAreaInput: function (e) {
    this.setData({
      content: e.detail.value,
    });
  },

  async toSubmit() {
    const that = this;
    const { content, temp, choose } = this.data;

    if (!content) {
      wx.showToast({
        title: "请输入评价内容",
        icon: "none",
      });
      return;
    }
    // const params = {
    //   userId: wx.getStorageSync("userInfo").userId,
    //   userName: wx.getStorageSync("userInfo").userName,
    //   userPhoto: wx.getStorageSync("userInfo").avatar,
    //   evaluateContent: content,
    // };
    // const table = "evaluate";
    // const res = await add(params, table);
    // if (res.code === 200) {
    //   wx.showToast({
    //     title: "评价成功",
    //     icon: "success",
    //   });
    //   setTimeout(() => {
    //     wx.navigateBack();
    //   }, 1500);
    // }
    const uploadFiles = temp.filter(
      (path) => path && path !== "../../img/pic.png"
    );
    const imageUrls = [];

    const uploadImage = (i) => {
      if (i < uploadFiles.length) {
        wx.uploadFile({
          url: app.globalData.baseUrl + "/common/upload", // 假设的图片上传接口
          filePath: uploadFiles[i],
          name: "file",
          success: (res) => {
            console.log("上传成功", JSON.parse(res.data));

            const data = JSON.parse(res.data);
            if (data.code === 200) {
              imageUrls.push(data.url); // 假设返回的图片URL在data.data.url
              uploadImage(i + 1);
            } else {
              wx.showToast({
                title: "图片上传失败",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            console.error("图片上传失败", err);
            wx.showToast({
              title: "图片上传失败",
              icon: "none",
            });
          },
        });
      } else {
        // 所有图片上传完毕，提交评价数据
        that.submitEvaluation(content, imageUrls.join(","), choose);
      }
    };

    if (uploadFiles.length > 0) {
      uploadImage(0);
    } else {
      that.submitEvaluation(content, "", choose);
    }
  },
  async submitEvaluation(content, imageUrls, isAnonymous) {
    const { add } = require("../../api/index.js"); // 引入api
    const data = {
      evaluateContent: content,
      evaluatePhoto: imageUrls, // 图片URL，如果有多张，可以逗号分隔
      isAnonymous: isAnonymous ? 1 : 0, // 匿名评价，1为是，0为否
      // 其他可能需要的字段，例如订单ID、商品ID等，根据实际接口需求添加
      // orderId: 'xxx',
      // goodsId: 'xxx'
    };

    // const { content, temp, choose } = this.data;

    if (!content.trim()) {
      wx.showToast({
        title: "请输入评价内容",
        icon: "none",
      });
      return;
    }
    let params = {
      userId: wx.getStorageSync("userInfo").userId,
      userName: wx.getStorageSync("userInfo").userName,
      userPhoto: wx.getStorageSync("userInfo").avatar,
      evaluateContent: content,
      evaluatePhoto: imageUrls,
      standby1: this.formatTime(),
    };
    const orderList = wx.getStorageSync("order").detail;
    orderList.forEach(async (item) => {
      params.goodsId = item.goodsId;
      const table = "evaluate";
      const res = await add(params, table);
      if (res.code === 200) {
        // wx.showToast({
        //   title: "评价成功",
        //   icon: "success",
        // });
      }
    });
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },
  formatTime() {
    const now = new Date();

    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始需+1
    const day = String(now.getDate()).padStart(2, "0");

    const hours = String(now.getHours()).padStart(2, "0");
    const minutes = String(now.getMinutes()).padStart(2, "0");
    const seconds = String(now.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  del: function (e) {
    var i = e.currentTarget.dataset.id;
    if (i == 0) {
      if (this.data.imgPath != "../../img/pic.png") {
        this.setData({
          imgPath2: this.data.imgPath3,
          imgPath3: this.data.imgPath,
          imgPath: "../../img/pic.png",
          imgLen: this.data.imgLen - 1,
        });
      } else {
        this.setData({
          imgPath2: this.data.imgPath3,
          imgPath3: "",
          // imgPath2: '',
          imgLen: this.data.imgLen - 1,
        });
      }
    } else if (i == 1) {
      if (this.data.imgPath != "../../img/pic.png") {
        this.setData({
          imgPath3: this.data.imgPath,
          imgPath: "../../img/pic.png",
          imgLen: this.data.imgLen - 1,
        });
      } else {
        this.setData({
          imgPath3: "",
          imgLen: this.data.imgLen - 1,
        });
      }
    } else if (i == 2) {
      this.setData({
        imgPath: "../../img/pic.png",
        imgLen: this.data.imgLen - 1,
      });
    }
  },
});
